package marioarena;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * A ServletContextListener handling the initialization and destroying of the servlet.
 */
public class MyServletContextListener implements ServletContextListener{
	public final int REFRESH_RATE = 1000;

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		try{
			// create the timer and timer task objects
			Timer timer = new Timer();
			RefreshServersTimerTask task = new RefreshServersTimerTask();

			// get a calendar to initialize the start time
			Calendar calendar = Calendar.getInstance();
			Date startTime = calendar.getTime();

			// schedule the task to run hourly
			timer.scheduleAtFixedRate(task, startTime, REFRESH_RATE);

			// save our timer for later use
			servletContext.setAttribute ("timer", timer);
		} catch (Exception e) {
			servletContext.log ("Problem initializing the task that was to run every second: " + e.getMessage ());
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();

		// get our timer from the Context
		Timer timer = (Timer)servletContext.getAttribute ("timer");

		// cancel all pending tasks in the timers queue
		if (timer != null)
			timer.cancel();

		// remove the timer from the servlet context
		servletContext.removeAttribute ("timer");
	}

}
